<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="show" round z-index="104" custom-style="width: 100%;background:#ffffff;overflow: hidden; ">
            <view class="popup-content" >
                <!-- <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y :lower-threshold="80"> -->
                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between;padding:0px 24px;">
                        <view class="popupTitle"> 支付方式 </view>
                        <van-icon name="cross"  size="15" @click="closePopup" />
                    </view>
                    <!-- 积分   我的积分   -->
                    <view class="scoreBox">
                        <view class="myIntegralsBalance">我的积分：<img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/jinbi_gray1127.png" alt="" style="width: 10px; height: 10px; margin: 0px 5px;">{{ myIntegralsBalance }} </view>
                        <view class="maxSorce">本单支付最多可用  <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/jinbi_orange1128.png" alt="" style="width: 10px; height: 10px; margin: 0px 5px;"> {{ maxScore }} </view>
                    </view>
                    <view class="pay_select_box">
                        <view class="popup-sort">
                            <view class="popup-item" :class="{ active: current === index }" v-for="(item, index) in paySelectList" :key="index" @click="onClickPayment(index, $event)">
                                <span v-if="index===0"><img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png" alt="" style="width: 10px; height: 10px; margin-right:6px;">
                                    {{ Number(popupUseIntegrals).toLocaleString()  }} <span style="margin-left: 4px; margin-right: 4px;">+</span> ￥{{ needPayCashAmount==0 || needPayCashAmount=='0.00'?'0.00': popupCash }} </span>
                                <span v-if="index===1"> ￥{{ totalAmount }} </span>
                                <span v-if="index===2 && current!==index">  自定义积分支付 </span>
                                <view v-if="current===index && index===2" class="inputAV">                                
                                    <view style="display: flex;align-items: center;text-align: center;"> 
                                        <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png" alt="" style="width: 10px; height: 10px; margin-right:6px;">
                                        <input type="number" v-model.number="customize" @input="clickMaxVal" class="jifenInput" :style="{ width: inputWidth }" :min="0" :max="parseInt(numericMaxScore)">
                                    </view> 
                                    <!-- <van-field class="jifenInput"  :value="customize" :border="noBorder" hold-keyboard="true" custom-style="padding:0px;" @input="clickMaxVal" :min="0" :max="parseInt(maxScore)">
                                        <img slot="left-icon" src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png" alt="" style="width: 10px; height: 10px; margin-right:6rpx;" >
                                    </van-field> -->
                                    <view style="padding-left: 4px;" class="popup-act-item">+ <text>￥{{ other }}</text></view> 
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="tips" v-if="current===0">默认自动抵扣积分</view>
                    <view class="notips" v-else>
                        <view class="maxTips" v-if="current===2 &&customize>maxScore && customize <myIntegralsBalance">当前输入积分大于订单可用最大积分</view>
                        <view class="maxTips" v-if="current===2 &&customize <=maxScore && customize >myIntegralsBalance">超出拥有的积分</view>
                    </view>
                    <van-toast id="van-toast" />
                </view>
                <!-- </scroll-view> -->
                <view class="bottom">
                    <!-- <van-goods-action>
                        <van-goods-action-button color="#FF6203" text="确定" @click="onClickbutton" />
                    </van-goods-action> -->
                    <van-button type="primary" class="" @click="onClickbutton">确定</van-button>
                </view>
            </view>
        </van-popup>
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'
export default {
    props: {
        show: {
            type: Boolean,
            default: () => false
        },
        myIntegralsBalance:{
            type: [String, Number],
            default: 0
        },
        popupCash:{
            type: [String, Number],
            default: 0
        },
        maxScore:{
             type: [String, Number],
             default: 0
        },
        exchangeRate:{ //兑换率
            type: [String, Number],
            default: 0
        },
        needPayCashAmount:{
            type: [String, Number],
            default: 0
        },
        popupUseIntegrals:{
            type: [String, Number],
            default: 0
        }

    },
    data () {
        return {
            current: 0,
            title: '支付地址',
            // myIntegralsBalance: '300',
            // maxScore: '120', // 最多可用积分
            paySelectList: [
                {
                    key: 1,
                    text: 'score+money'
                },
                {
                    key: 2,
                    text: 'money'
                },
                {
                    key: 3,
                    text: '自定义'
                }
            ],
            useScore: '0',
            useMoeny: '0',
            // popupCash: '10',
            customize: '0', //自定义部分的积分
            other: '0', //自定义部分的现金
            // exchangeRate: '10'// 10 个积分兑换 1 块钱   存储积分与现金的兑换比例
            inputWidth: '28rpx', // 新增：动态宽度变量（初始值可设为默认宽度）
        }
    },

    computed: {
        // // 新增计算属性进行数值转换
        // numericMyIntegrals() {
        //     return parseFloat(this.myIntegralsBalance) || 0;
        // },
        // numericNeedPayCash() {
        //     return parseFloat(this.popupCash) || 0;
        // },
        // numericMaxScore() {
        //     return parseFloat(this.maxScore) || 0;
        // }
        numericMaxScore() {
            return Math.min(
                Number(this.maxScore),
                Number(this.myIntegralsBalance),
                Math.floor(Number(this.totalAmount) * this.exchangeRate)
            );
        },
        numericCashAmount() {
            return Number(this.popupCash);
        },

        totalAmount() { // 新增：计算总金额（现金 + 积分兑换的金额）
            const cash =  this.numericCashAmount;
            const score = Number(this.popupUseIntegrals); // 实际使用的积分（转换为数值）
            const rate = Number(this.exchangeRate); // 兑换率（转换为数值）
            const scoreToCash = score / rate; // 积分兑换的现金金额
            console.log(cash,score,rate,scoreToCash,'cash,score,rate,scoreToCash',(cash + scoreToCash).toFixed(2))
            if (Number(this.needPayCashAmount) == 0||this.needPayCashAmount=='0.00') {
                return  Number(cash); // 保留两位小数
            }else{
                return Number((cash + scoreToCash).toFixed(2)); // 保留两位小数
            }
        },
        // autoWidth() {
        //     const currentCustomize = this.customize
        //     const strLength = currentCustomize.toString().length; // 长度（如 3）
        //     console.log('输入的长度（方法2）:', strLength);
        //     // 计算输入框的宽度
        //     let width = 72
        //     width = strLength * 12 >72? strLength * 12 : 72
        //    console.log(width,'width',{ width: `${width}rpx`})
        //     return {
        //         width: `${width}rpx`
        //     };
        // }
    },

    watch: {
        numericCashAmount: {
            immediate: true,
            handler() {
                this.initDefaultPayment();
            }
        },
        totalAmount: {
            immediate: true,
            handler() {
                // this.initDefaultPayment();
                console.log(this.totalAmount,'val')
            }
        }

    },
    onLoad () {},
    onReady () {},

    methods: {

        // 关闭弹窗
        closePopup () {
            console.log('关闭 关闭关闭---------')
            this.$emit('closePayment')
        },

        // 确定
        onClickbutton() {
            if (this.current === 2 && this.customize > this.numericMaxScore) {
                Toast('积分输入超过可用上限');
                return;
            }
            let paymentData = {}
            switch (this.current) {
                case 0: // 积分+现金
                    paymentData = {
                        type: 'score',
                        score: this.numericMaxScore,
                        cash: (this.totalAmount - (this.numericMaxScore / this.exchangeRate)).toFixed(2)
                    }
                    break
                case 1: // 纯现金
                    paymentData = {
                        type: 'cash',
                        score: 0,
                        cash: this.totalAmount.toFixed(2)
                    }
                    break
                case 2: // 自定义
                    const validScore = Math.min(this.customize, this.maxScore, this.myIntegralsBalance);
                    paymentData = {
                        type: 'custom',
                        score:Number(validScore),
                        cash: (this.totalAmount - (validScore / this.exchangeRate)).toFixed(2),
                        // cash: Math.max(0, this.other).toFixed(2)
                    }
                    break
            }
            console.log(paymentData,'paymentData')
            this.$emit('confirm', paymentData,this.current)
            this.closePopup()
        },
        // 初始化默认支付方式
        initDefaultPayment() {
            const maxScore = this.numericMaxScore;
            const exchangeMoney = maxScore / this.exchangeRate;
            this.useMoeny = Math.max(0, this.totalAmount - exchangeMoney).toFixed(2);
            this.other = this.useMoeny;
            this.current = maxScore > 0 ? 0 : 1;
            this.customize = maxScore;
        },

        // 积分 + 现金
        calculateDefaultPayment() {
            // 自动计算最大可用积分对应的现金
            const maxScore = this.numericMaxScore;
            const cash = this.totalAmount - (maxScore / this.exchangeRate);

            this.useMoeny = cash > 0 ? cash.toFixed(2) : '0';
            this.other = cash > 0 ? cash.toFixed(2) : '0';

            // 当选择第一个选项时自动更新
            if (this.current === 0) {
                this.customize = maxScore;
            }
        },


        // 自定义支付

        // 支付方式选择
        onClickPayment (val, e) {
            if (this.current === val) return; // 相同选项不重复触发
            this.current = val

            if (val === 2) {
                this.customize = Math.min(this.numericMaxScore, this.totalAmount * this.exchangeRate);
                // 当切换到自定义支付时，计算初始宽度
                const initialLength = this.customize.toString().length; // 获取初始值长度
                this.inputWidth = `${initialLength * 14}rpx`; // 根据长度动态计算宽度（示例：每个字符占24rpx）
            }
            this.calculateOther();
        },

    //    // 输入积分时计算剩余需要支付的现金
    //     clickMaxVal(e) {
    //         //    let inputScore = parseInt(e.target.value);
    //         //    if (isNaN(inputScore)) {
    //         //        inputScore = 0;
    //         //    }
    //         //    // 限制输入范围在 0 到 maxScore 之间
    //         //    inputScore = Math.max(0, Math.min(inputScore, parseInt(this.maxScore)));
    //         //    this.customize = inputScore.toString() || 0
    //         //     // this.customize = e.target.value || 0;
    //         //     this.calculateOther();

    //         let value = parseInt(e.detail.value) || 0;
    //         if (!this.validateInput(value)) {
    //             Toast('超过可用积分上限');
    //             value = Math.min(value, Math.min(this.maxScore, this.myIntegralsBalance));
    //         }
    //         console.log(value,'value')
    //         this.customize = value;
    //         this.calculateOther();
    //     },

    //     // 计算剩余需要支付的现金
    //     calculateOther () {
    //         const inputScore = parseInt(this.customize) || 0
    //         if (!isNaN(inputScore)) {
    //             const exchangeMoney = Math.floor(inputScore / this.exchangeRate);
    //             this.other = Math.max(0, this.popupCash - exchangeMoney);
    //         }else{
    //             console.error('计算剩余金额时出现错误，popupCash 不是有效的数字。');
    //             this.other = 0;
    //         }
    //     },

        // 优化输入处理
        clickMaxVal(e) {
            const inputValue = Number(e.detail.value) || 0;
            // console.log(inputValue, 'inputValue')
            // // 实时计算当前最大可用值（每次输入都重新计算）
            // const currentMax = Math.min(
            //     Number(this.maxScore),
            //     Number(this.myIntegralsBalance),
            //     Math.floor(Number(this.popupCash) * this.exchangeRate)
            // );
            // // 实时校验并修正（每次输入都执行）
            // let validValue = Math.max(0, Math.min(inputValue, currentMax));
            // // 使用 this.$set 确保响应式更新
            // this.$set(this, 'customize', validValue);
            // // 当接近上限时给予提示（达到上限的90%时预警）
            // if (validValue >= Number(this.myIntegralsBalance) * 0.9) {
            //     Toast(`剩余可用积分 ${Number(this.myIntegralsBalance) - validValue}`);
            // }

            const maxAvailable = this.numericMaxScore;
            const validValue = Math.min(Math.max(inputValue, 0), maxAvailable);

            // 动态调整输入框宽度
            const inputLength = String(validValue).length; // 输入值的字符长度
            if (inputLength <= 3) {
                this.inputWidth = '72rpx'; // 短内容时宽度较小
            } else {
                const strLength = inputLength * 12
                this.inputWidth = `${strLength}rpx`; // 长内容时宽度增大
            }
            console.log(this.inputWidth,'this.inputWidth---')

            if (inputValue > maxAvailable) {
                Toast(`最大可用积分为${maxAvailable}`);
            }
            this.customize = validValue;
            // 处理非法输入（非数字）
            if (isNaN(inputValue)) {
                this.customize = 0
            }
            console.log(this.customize,'this.customize')
            // this.calculateOther();
            // 立即执行视图更新
            this.$nextTick(() => {
                this.calculateOther();
            });
        },

        // 优化现金计算
        calculateOther() {
            const inputScore = Number(this.customize).toFixed(2) || 0;
            const exchangeMoney = inputScore / this.exchangeRate;
            this.other = (this.totalAmount - exchangeMoney).toFixed(2);
        },
        // 新增数据校验方法
        validateInput() {
            return this.customize <= this.maxScore &&
                this.customize <= this.myIntegralsBalance
        },
        // // 封装积分验证逻辑
        // validateScoreInput(score) {
        //     const maxAvailable = Math.min(this.maxScore, this.myIntegralsBalance);
        //     return score >= 0 && score <= maxAvailable;
        // },

    }

}
</script>
<style lang="scss" scoped>

::v-deep .van-button__text {
    // display: inline-block;
    display: flex !important;
    flex-direction: column !important;
}
// 提示框
.popup-content {
    padding: 24px 0px;  //页面底部有提示框  这里不可写左右内边距24px
    font-size: 12px;
    background:#ffffff;
    border-radius: 16px;
    overflow: hidden;
    height: 100%;

    .popup-main {
        height: 100%;
        padding-bottom: 72px;
    }

    .popupTitle {

        font-size: 20px;
        text-align: left;
        color: #111111;
        line-height: 20px;
    }

    .scoreBox{
        margin-top: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding:0px 24px;

        .myIntegralsBalance{
            font-size: 12px;
            text-align: left;
            color: #737373;
            line-height: 12px;
        }
        .maxSorce{
            // margin-left: 40px;
            font-size: 12px;
            text-align: right;
            color: #FF6203;
            line-height: 12px;
        }
    }
    .pay_select_box{
        padding:0px 24px 22px 24px;
        margin-top:28px;
        // padding-bottom: 22px;
    }
    .popup-sort {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        }
        .popup-item{
            // position: relative; // 新增定位上下文
            margin-right: 14px;
            margin-bottom: 14px;
            height: 30px;
            line-height: 30px;
            min-width: 45%;
            color: #111111;
            font-size: 12px;
            border: 1px solid #D4D4D4;
            text-align: center;

            &.active {
                border: 1px solid #333333;
        
                // &::after {
                //     content: '✓';
                //     position: absolute;
                //     right: 12px;
                //     color: #FF6203;
                // }
            }
        }
        // .popup-item:last-child{
        //     margin-bottom: 0px;
        // }
        // .popup-item:nth-child(2n) {
        //     margin-right: 0px;
        // }
        .popup-act-item{
            color: #999999;
            font-size: 12px;
            display: flex;
            align-items: center;
        }

}
.inputAV{
    font-size: 12px;
    display: flex;
    align-items: center;
    text-align: center;
    // padding-left:40rpx;
    justify-content: center;
}
.jifenInput{
    // width: 72rpx;
}
// 去绑定的按钮
.button{
    // width: 100%;
    font-size: 12px;
    color: #ffffff;
    height: 20px;
    line-height:20px;
    border-radius: 10px;
    border-style: initial !important;
    padding: 0 11px !important;
    background: #FF6203 !important;
    margin-left: 13px;
}


.tips{
    // position: fixed;
    width: 100%;
    height: 35px;
    line-height: 35px;
    background: #FFF9F7;
    // bottom: 105px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    text-align: center;
    color: #FF6203;
    z-index: 999;
}
.notips{
    width: 100%;
    height: 35px;
    line-height: 35px;
    background-color: transparent;
}
.maxTips{
    font-size: 12px;
    text-align: center;
    color: #FF6203;
}
::v-deep .van-cell {
    border: none;
    display: flex;
    align-items: center !important;
    width: 72rpx;
    background: transparent;
}
::v-deep .van-cell--hover .hover-class{
    border: 1px solid #888888;
}

::v-deep .van-cell, .van-cell--borderless{
    height: 30px !important;
    line-height: 30px !important;
    font-size: 12px !important;
    text-align: center;
    padding: 0px !important;
    display: flex;
    align-items: center !important;

}
::v-deep .van-cell__value {
    overflow:auto !important;
    display: flex !important;

}
::v-deep .van-field__control, .field-index--van-field_control {
    height: 30px !important;
    line-height: 30px !important;
}
::v-deep .van-button--primary {
  width: 100%;
  height: 86rpx;
  border-radius: 50rpx;
  background: #ff6203;
  margin-top: 32rpx;
  font-size: 28rpx;
}
.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}
</style>
